<template>
  <div class="result-container">
    <div class="result-header">
      <h2>成绩管理</h2>
      <div class="header-buttons" v-if="userStore.role !== 'student'">
        <el-button type="primary" @click="handleGenerateReport">成绩册生成</el-button>
        <el-button type="primary" @click="handleAdd">录入成绩</el-button>
      </div>
    </div>

    <!-- 成绩列表 -->
    <el-table :data="resultList" v-loading="loading" border>
      <el-table-column prop="eventName" label="赛事名称" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="score" label="成绩" />
      <el-table-column v-if="userStore.role !== 'student'" label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 录入/修改成绩对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '修改成绩' : '录入成绩'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="赛事项目" prop="eventId">
          <el-select 
            v-model="form.eventId" 
            placeholder="请选择赛事项目"
            style="width: 100%"
            :disabled="!!form.id"
          >
            <el-option 
              v-for="item in eventOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参赛者" prop="name">
          <el-select
            v-model="form.name"
            placeholder="请选择参赛者"
            style="width: 100%"
            :disabled="!!form.id"
          >
            <el-option
              v-for="item in participantOptions"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成绩" prop="score">
          <el-input v-model="form.score" placeholder="请输入成绩" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成绩册预览对话框 -->
    <el-dialog
      v-model="reportVisible"
      title="成绩册预览"
      width="800px"
    >
      <div class="report-content">
        <h3>比赛成绩册</h3>
        <el-table :data="reportData" border>
          <el-table-column prop="eventName" label="赛事名称" />
          <el-table-column prop="name" label="参赛者" />
          <el-table-column prop="score" label="成绩" width="100" />
          <el-table-column prop="rank" label="排名" width="80" align="center" />
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleExportReport">导出</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 列表相关
const loading = ref(false)
const resultList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 赛事选项
const eventOptions = ref([
  { id: 1, name: '100米跑' },
  { id: 2, name: '200米跑' },
  { id: 3, name: '跳高' },
  { id: 4, name: '跳远' }
])

// 参赛者选项（模拟数据）
const participantOptions = ref([
  { name: '张三' },
  { name: '李四' },
  { name: '王五' }
])

// 模拟数据
const fetchData = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    resultList.value = [
      {
        id: 1,
        eventName: '100米跑',
        name: '张三',
        score: '11.2'
      }
    ]
    total.value = 1
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 录入/修改成绩相关
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)

const form = reactive({
  id: '',
  eventId: '',
  name: '',
  score: ''
})

const rules = {
  eventId: [{ required: true, message: '请选择赛事项目', trigger: 'change' }],
  name: [{ required: true, message: '请选择参赛者', trigger: 'change' }],
  score: [{ required: true, message: '请输入成绩', trigger: 'blur' }]
}

// 录入成绩
const handleAdd = () => {
  form.id = ''
  form.eventId = ''
  form.name = ''
  form.score = ''
  dialogVisible.value = true
}

// 修改成绩
const handleEdit = (row) => {
  form.id = row.id
  form.eventId = eventOptions.value.find(item => item.name === row.eventName)?.id
  form.name = row.name
  form.score = row.score
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await new Promise(resolve => setTimeout(resolve, 1000))
        ElMessage.success(form.id ? '修改成功' : '录入成功')
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error(form.id ? '修改失败' : '录入失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 成绩册相关
const reportVisible = ref(false)
const reportData = ref([])

const handleGenerateReport = async () => {
  try {
    // 模拟获取成绩册数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    reportData.value = [
      {
        eventName: '100米跑',
        name: '张三',
        score: '11.2',
        rank: 1
      },
      {
        eventName: '100米跑',
        name: '李四',
        score: '11.5',
        rank: 2
      }
    ]
    reportVisible.value = true
  } catch (error) {
    ElMessage.error('生成成绩册失败')
  }
}

const handleExportReport = () => {
  ElMessage.success('成绩册导出成功')
  reportVisible.value = false
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.result-container {
  padding: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.report-content {
  h3 {
    text-align: center;
    margin-bottom: 20px;
  }
}
</style> 